package com.cupdata.zicon.jdk7concurrent.chapter4;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * An important point to consider is that the period between two executions is
 * the period of time between these two executions that begins. If you have a
 * periodic task that takes 5 sceconds to execute and you put a period of 3
 * seconds, you will have two instances of the task executing at a time.
 * 
 * The method scheduleAtFixedRate() returns a ScheduledFuture object, which
 * extends the Future interface, with methods to work with scheduled tasks.
 * ScheduledFuture is a parameterized interface. In this example, as your task
 * is a Runnable object that is not parameterized, you have to parameterize them
 * with the ? symbol as a parameter.
 * 
 * @author SunYabing
 *
 */
public class RunTaskPeriodically {

	public RunTaskPeriodically() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		System.out.printf("Main: Starting at: %s\n", new Date());

		Task123 task = new Task123("Task");
		ScheduledFuture<?> result = executor.scheduleAtFixedRate(task, 1, 2,
				TimeUnit.SECONDS);
		for (int i = 0; i < 10; i++) {
			System.out.printf("Main: Delay: %d\n",
					result.getDelay(TimeUnit.MILLISECONDS));
			// Sleep the thread during 500 milliseconds.
			try {
				TimeUnit.MILLISECONDS.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		executor.shutdown();
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Main: Finished at: %s\n", new Date());
	}

}

class Task123 implements Runnable {
	private String name;

	public Task123(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		System.out.printf("%s: Starting at : %s\n", name, new Date());
		// return "Hello, world";

	}

}
